<!-- 
/*
 * @Copyright (c) 2018 缪聪(mcg-helper@qq.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");  
 * you may not use this file except in compliance with the License.  
 * You may obtain a copy of the License at  
 *     
 *     http://www.apache.org/licenses/LICENSE-2.0  
 *     
 * Unless required by applicable law or agreed to in writing, software  
 * distributed under the License is distributed on an "AS IS" BASIS,  
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
 * See the License for the specific language governing permissions and  
 * limitations under the License.
 */
 -->
 
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
%>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width">
		<link rel="shortcut icon" type="image/png" href="../../img/favicon.png">
        <title>微克机器人</title>
		
	</head>
	
	<body>
		<div id="mcg_body" class="container-fluid autoHeight">
			<div class="row autoHeight">
			        <div id="scheduletoolbar" class="btn-group">
			        	<button id="schedule_create_task_btn" class="btn btn-default">
			        		<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>创建任务
			        	</button>
			        	<!-- 
			            <button id="btn_edit" type="button" class="btn btn-default">
			                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
			            </button>
			            <button id="btn_delete" type="button" class="btn btn-default">
			                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
			            </button>
			             -->
			        </div>
				<div class="col-md-12 autoHeight">

			        <table id="scheduleListTable"
			               data-toggle="table"
			               data-height="460"
			               data-show-columns="true"
			               data-search="true" 
			               data-unique-id="taskId"      
				           data-pagination="true"
				           data-page-size="5"
				           data-page-list="[5,10,20,30]"
				           data-pagination-first-text="上一页"
				           data-pagination-pre-text="上一页"
				           data-pagination-next-text="下一页"
				           data-pagination-last-text="尾页">
			            <thead>
			            <tr>
			            	<th data-field="name">作业名称</th>
			            	<th data-field="startTime" data-formatter="scheduleDateFormat">最近一次执行开始时间</th>
			            	<th data-field="endTime" data-formatter="scheduleDateFormat">最近一次执行结束时间</th>
			            	<th data-field="createDate" data-formatter="scheduleDateFormat">创建时间</th>
			            	<th data-field="modifyDate" data-formatter="scheduleDateFormat">修改时间</th>
			            	<th data-field="planStatus" data-formatter="planStatusFormat">执行状态</th>
			            	<th data-field="commands" data-formatter="scheduleCommandsFormatter">操作</th>
			            </tr>
			            </thead>
			        </table>
				</div>
			</div>
	 	</div>
	</body>
</html>
<script type="text/javascript">
var scheduleListTable = null;
$(function () {
	$('#schedule_create_task_btn').click(function(data){
		var param = {"modalId":Math.uuid() + "_createTask_Modal", "taskId":null, "option":{"title":"创建任务", "width":1100} };
		common.showAjaxDialog("/schedule/initCreateTaskModal", setCreateTaskDialogBtns(param), createTaskModalCallBack, null, param);
	});
	scheduleListTable = $("#scheduleListTable").bootstrapTable({toolbar:'#scheduletoolbar'});
	queryScheduleList();
});

function queryScheduleList() {
	scheduleListTable.bootstrapTable("removeAll");
	common.ajax({
		url : "/schedule/getAll",
		type : "POST",
		data : null,
		contentType : "application/json"
	}, function(data) {
		if(data != null && data.statusCode == 1) {
			if(data.resultMap != null && data.resultMap.dataList != null) {
				for(var i=0; i<data.resultMap.dataList.length; i++) {
					scheduleListTable.bootstrapTable('append', data.resultMap.dataList[i]);
				}
			}
		} else {
			Messenger().post({
				message: data.statusMes,
				type: "error",
				hideAfter: 5,
			 	showCloseButton: true
			});
		}
		
	});
}

function scheduleCommandsFormatter(value, row, index) {
  	var btns = '<div class="btn-group">';
  			if(row.planStatus == "-1" || row.planStatus == "0") {
  				btns += '<button type="button" onClick="taskStart(\'' + row.taskId + '\');" class="btn btn-default">启动</button>';
  			} else if(row.planStatus == "1") {
  				btns += '<button type="button" onClick="taskStop(\'' + row.taskId + '\');" class="btn btn-default">停止</button>';
  			}
  			btns += '<button type="button" onClick="taskEdit(\'' + row.taskId + '\');" class="btn btn-default">编辑</button>';
  			btns += '<button type="button" onClick="taskDelete(\'' + row.taskId + '\');" class="btn btn-default">删除</button>';
  			btns += '</div>';

	return btns;
}

function taskDelete(taskId) {
	common.ajax({
		url : "/schedule/taskDelete",
		type : "POST",
		data : "taskId=" + taskId
	}, function(data) {
		if(data != null && data.statusCode == 1) {
			queryScheduleList();
			/*
			$("#scheduleListTable").bootstrapTable('remove', {
                field: 'id',
                values: [id]
            });
			*/
			Messenger().post({
				message: data.statusMes,
				type: "success",
				hideAfter: 5,
			 	showCloseButton: true
			});
		} else {
			Messenger().post({
				message: data.statusMes,
				type: "error",
				hideAfter: 5,
			 	showCloseButton: true
			});
		}
		
	});
	
}

function taskStart(taskId) {
	var sTimetask = $("#scheduleListTable").bootstrapTable('getRowByUniqueId', taskId);
	
	common.ajax({
		url : "/schedule/taskStart",
		type : "POST",
		data : JSON.stringify(sTimetask),
		contentType : "application/json"
	}, function(data) {
		if(data != null && data.statusCode == 1) {
			queryScheduleList();
			Messenger().post({
				message: data.statusMes,
				type: "success",
				hideAfter: 5,
			 	showCloseButton: true
			});
		} else {
			Messenger().post({
				message: data.statusMes,
				type: "error",
				hideAfter: 5,
			 	showCloseButton: true
			});
		}
		
	});
	
}

function taskStop(taskId) {
	var sTimetask = $("#scheduleListTable").bootstrapTable('getRowByUniqueId', taskId);
	
	common.ajax({
		url : "/schedule/taskStop",
		type : "POST",
		data : JSON.stringify(sTimetask),
		contentType : "application/json"
	}, function(data) {
		if(data != null && data.statusCode == 1) {
			queryScheduleList();
			Messenger().post({
				message: data.statusMes,
				type: "success",
				hideAfter: 5,
			 	showCloseButton: true
			});
		} else {
			Messenger().post({
				message: data.statusMes,
				type: "error",
				hideAfter: 5,
			 	showCloseButton: true
			});
		}
		
	});
	
}

function taskEdit(taskId) {
	var param = {"modalId":Math.uuid(), "taskId":taskId, "option":{"title":"编辑任务", "width":1100} };
	common.showAjaxDialog("/schedule/initCreateTaskModal", setCreateTaskDialogBtns(param), createTaskModalCallBack, null, param);
}

function createTaskModalCallBack(param) {
	$(".selectpicker").selectpicker({
		noneSelectedText: "请选择",
		liveSearch: true,
		width:"100%"
	});
	
	var schedule_setting = {
	        view: {
	            selectedMulti: false
	        },
	    	callback: {
	    		onClick: scheduleFlowSelected
	    	},
	        check: {
	            enable: false
	        },
	        data: {
	            simpleData: {
	                enable: true
	            }
	        }
	};

	common.ajax({
		url : "/flowTree/getDatas",
		type : "GET",
		data : null,
		contentType : "application/json"
	}, function(data) {
		var flowTreeName = param.modalId + "_flowTree";
    	$.fn.zTree.init($("#" + flowTreeName), schedule_setting, data.topologys);
    	var treeObj = $.fn.zTree.getZTreeObj(flowTreeName);
    	treeObj.expandAll(true);
    	
    	if(param.taskId != null) {
    		common.ajax({
    			url : "/schedule/getTask",
    			type : "POST",
    			data : "taskId=" + param.taskId
    		}, function(data) {
    			if(data.statusCode == 1) {
    				if(data.resultMap.sTimetask != null) {
    					common.formUtils.setValues(param.modalId + "_task_create_form", {"sTimetask":data.resultMap.sTimetask});
    				}
    				
    				var flowTreeName = param.modalId + "_flowTree";
    		    	var treeObj = $.fn.zTree.getZTreeObj(flowTreeName);
    				var rootNode = treeObj.getNodeByParam("id", data.resultMap.sTimetask.flowId, null);
    				if(rootNode != null) {
    					$("#" + param.modalId + "_flowName").html(rootNode.name+"&nbsp;<span class='caret'></span>");
    			    	treeObj.selectNode(rootNode);
    				}
    			}
    		});	
    	}
	});
	

}

function setCreateTaskDialogBtns(param) {
	return buttons = [
		{
			class: "btn btn-primary",
			text: "保存",
			click: function() {
				var _this = this;
				var sTimetask = $("#" + param.modalId + "_task_create_form").serializeJSON();
				var result = JSON.parse(sTimetask);
				common.ajax({
					url : "/schedule/taskSave",
					type : "POST",
					data : JSON.stringify(result.sTimetask),
					contentType : "application/json"
				}, function(data) {
					if(data.statusCode == 1) {
						queryScheduleList();
						/*
						var scheduleListTable = $("#scheduleListTable").bootstrapTable({});
						scheduleListTable.bootstrapTable('append', data.resultMap.sTimetask);
						*/
						$( _this ).dialog( "destroy" );
					}
				});					
			}
		},
		{
			class: "btn btn-default",			
			text: "关闭",
			click: function() {
				$( this ).dialog( "destroy" );
			}
		}
	];
	
}

function scheduleDateFormat(value) {
	if(value == undefined || value == "undefined") {
		return "";
	}
	return common.dateUtils.getFormatDateByLong(value, "yyyy-MM-dd hh:mm:ss");
}

function planStatusFormat(planStatus) {
	if(planStatus == "1") {
		return "<span class='label label-sm label-success'>运行中</span>";	
	} else if(planStatus == "0") {
		return "<span class='label label-sm label-danger'>已停止</span>";	
	} else if(planStatus == "-1") {
		return "<span class='label label-sm label-warning'>未启动</span>";	
	}  else {
		return "<span class='label label-sm label-danger'>未知状态</span>";
	}
}

function scheduleFlowSelected(event, treeId, treeNode) {
	
	var modalFlowTreeId = treeNode.tId.substring(0, treeNode.tId.indexOf("_flowTree"));
	$("#" + modalFlowTreeId + "_flowName").html(treeNode.name+"&nbsp;<span class='caret'></span>");
	$("#" + modalFlowTreeId + "_flowId").val(treeNode.id);
}


</script>
